import axios from 'axios'
import { getToken } from './token'
import { message, notification } from 'ant-design-vue'
import router from '@/router'
import { useStore } from '@/store'

const request = axios.create({
  // API 请求的默认前缀
  baseURL: import.meta.env.VITE_BASE_URL as string,
  timeout: 6000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

request.interceptors.request.use((config) => {
  const token = getToken()
  if (token && config.headers) {
    config.headers.Authorization = 'Bearer ' + token
 }
 return config
}, errorHandler)

request.interceptors.response.use(response => {
  if (response.status === 200) {
    if (response.data.code !== 200) {
      message.error(response.data.err)
      return Promise.reject('')
    } else {
      return response.data
    }
  }
  return Promise.reject('未知错误，请稍后重试')
}, errorHandler)

// 异常拦截处理器
function errorHandler(error) {
  if (!error.response) {
    // TODO: 是否需要换成确认框重新刷新的操作
    notification.error({
      message: '请求超时',
      description: `${error.toString()}`
    })
    return Promise.reject(error)
  }
  // const data = error.response.data
  // 从 localstorage 获取 token
  const token = getToken()
  const statusCode = error.response.status
  const data = error.response.data
  const { userStore } = useStore()
  if (statusCode === 401) {
    notification.error({
      message: 'Unauthorized',
      description: 'Authorization verification failed'
    })
    if (token) {
      userStore.handleLogout().then(() => {
        setTimeout(() => {
          router.replace('/login')
        }, 1500)
      })
    } else {
      setTimeout(() => {
        router.replace('/login')
      }, 1500)
    }
  }
  const { code, err } = data
  switch (code) {
    case 501: {
      notification.error({
        message: err
      })
      break
    }
    case 402:
      notification.error({
        message: '重新登录',
        description: '长时间未操作，请重新登录'
      })
      userStore.handleLogout().then(() => {
        setTimeout(() => {
          router.replace('/login')
        }, 1500)
      })
      break
    default:
      notification.error({
        message: '接口请求错误',
        description: `状态码${statusCode || error.toString()}`
      })
  }
  return Promise.reject(error)
}

export default request
